package com.evaluation.dao.config;

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import jakarta.persistence.EntityManagerFactory;

@Configuration(proxyBeanMethods = false)
//值越小，越优先执行 ,要优于事务的执行 ,在启动类中加上了@EnableTransactionManagement(order = 10)
@EnableTransactionManagement(order = 10)
@EnableJpaRepositories(value = "com.evaluation.**.dao",
							entityManagerFactoryRef = "evalEntityManagerFactory", 
							transactionManagerRef = "evalTransactionManager")
public class EvalDataSourceManager {
	//@Autowired
	private JpaProperties jpaProperties;
	
	//@Autowired
	private DataSource dataSource;
	
	public EvalDataSourceManager( JpaProperties jpaProperties, DataSource dataSource ) {
		this.jpaProperties = jpaProperties;
		this.dataSource = dataSource;
	}

	/**
	 * EntityManagerFactory类似于Hibernate的SessionFactory,mybatis的SqlSessionFactory
	 * 总之,在执行操作之前,我们总要获取一个EntityManager,这就类似于Hibernate的Session,
	 * mybatis的sqlSession.
	 * 
	 * @return
	 */
	@Bean(name = "evalEntityManagerFactory")
	@Primary
	public EntityManagerFactory evalEntityManagerFactory(  ) {
		HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
		LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
		factory.setJpaVendorAdapter(vendorAdapter);
		factory.setPackagesToScan("com.evaluation.**.bean");
		factory.setDataSource( dataSource );// 数据源
		factory.setJpaPropertyMap(jpaProperties.getProperties());
		factory.afterPropertiesSet();	// 在完成了其它所有相关的配置加载以及属性设置后,才初始化
		
		return factory.getObject();
	}
	

	/**
	 * 配置事物管理器
	 * 
	 * @return
	 */
	@Bean(name = "evalTransactionManager")
	@Primary
	public PlatformTransactionManager writeTransactionManager() {
		JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
		
		jpaTransactionManager.setEntityManagerFactory(this.evalEntityManagerFactory());
		
		return jpaTransactionManager;
	}
}
